using System.Reflection;
using Microsoft.AspNetCore.Authorization;
using Microsoft.OpenApi.Models;
using PiggyBankCashFlowApi.Ext;
using PiggyBankCashFlowApi.Middleware;
using PiggyBankCashFlowApi.Repo;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(opt => {
    opt.AddSecurityDefinition("JwtBearer999", new OpenApiSecurityScheme()
    {
        Description = "请求头中输入Jwt口令",
        Name = "Authorization",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.Http,
        Scheme = "Bearer"

    });
    var scheme = new OpenApiSecurityScheme
    {
        Reference = new OpenApiReference()
        { 
            Id = "JwtBearer999",
            Type = ReferenceType.SecurityScheme
        }
    };
    opt.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        { scheme,Array.Empty<string>()}
    });
});
builder.Services.AddHttpContextAccessor();
//setup Jwt Authentication
builder.AddJwtAuthenticationAndAuthorization();

builder.Services.AddScoped<CashFlowRepo>(provider => new CashFlowRepo(
    builder.Configuration.GetConnectionString("DefaultConnection") ??
    throw new Exception("Db connection string not foud"),
    provider.GetRequiredService<ILogger<CashFlowRepo>>()));

builder.Services.AddMediatR(config =>
{
    config.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly());
});



var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseMiddleware<GlobalExceptionHandlerMiddleware>();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();

//These are for debug only:
// app.UseMiddleware<AuthenticationDiagnosticsMiddleware>();
// app.UseMiddleware<AuthenticationLoggingMiddleware>();


app.MapControllers();

app.Run();